package com.vanke.kotlin_mvp.statistics

import com.vanke.kotlin_mvp.data.Task
import com.vanke.kotlin_mvp.data.TaskDataSource
import com.vanke.kotlin_mvp.data.TaskRepository

/**
 * @name Kotlin_MVP
 * @package name：com.vanke.kotlin_mvp.statistics
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/22 14:35
 */
class StatisticsPresenter(val taskRepository: TaskRepository,
                          val statisticView: StatisticsContract.View)
    : StatisticsContract.Presenter{

    init {
        statisticView.presenter = this
    }
    override fun start() {
        loadStatistics()
    }

    private fun loadStatistics() {
        statisticView.setProgressIndicator(true)

        taskRepository.getTasks(object : TaskDataSource.LoadTaskCallback{
            override fun onTaskLoaded(tasks: List<Task>) {
                val completedTasks = tasks.filter { it.isCompleted }.size
                val activeTasks = tasks.size - completedTasks

                if (!statisticView.isActive){
                    return
                }

                statisticView.setProgressIndicator(false)

                statisticView.showStatistics(activeTasks,completedTasks)
            }

            override fun onDataNotAvailable() {
                if (!statisticView.isActive){
                    return
                }
                statisticView.showLoadingStatisticsError()
            }

        })
    }

}